package cn.wolfcode.education.service.impl;

import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.domain.NetDisk;
import cn.wolfcode.education.mapper.NetDiskMapper;
import cn.wolfcode.education.service.INetDiskService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class NetDiskServiceImpl implements INetDiskService {

    @Autowired
    private NetDiskMapper netDiskMapper;

    public void update(NetDisk netDisk) {

    }

    public NetDisk selectByPrimaryKey(Long id) {
        return null;
    }

    //根据用户查看相应的目录文件
    public List<NetDisk> queryAllParent() {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if(employee.isAdmin()){
            return netDiskMapper.getAllParentNetDisk();
        }else{
            return netDiskMapper.queryAllParentByEmployee(employee.getId());
        }
    }

    //上传文件
    public void upload(MultipartFile fileImport, String basePath,Long parentId,String file) {
        NetDisk netDisk = new NetDisk();
            netDisk.setName(file);
            netDisk.setCreateTime(new Date());
            netDisk.setUrl(basePath);
            netDisk.setEmployee((Employee) SecurityUtils.getSubject().getPrincipal());
        if(parentId != null) {
            netDisk.setParentId(parentId);
        }
        netDiskMapper.insert(netDisk);
    }

    //删除文件
    public void delete(Long id) {
        //获取要被删除的文件或文件夹
        NetDisk netDisk = netDiskMapper.selectByPrimaryKey(id);
        //现将其文件或文件夹删除
        netDiskMapper.deleteByPrimaryKey(id);
        //如果它是一个文件夹
        if(netDisk.getChildrens().size() != 0){
            //则删除该文件夹中所有的文件以及文件夹
            netDiskMapper.deleteAllChildren(id);
        }
    }

    //新建文件夹
    public void save(String fileName,Long id) {
        NetDisk netDisk = new NetDisk();
        netDisk.setCreateTime(new Date());
        netDisk.setName(fileName);
        netDisk.setEmployee((Employee) SecurityUtils.getSubject().getPrincipal());
        netDisk.setParentId(id);
        netDiskMapper.insert(netDisk);
    }
}
